﻿using System;
using System.Linq;
using Framework;
using HtmlAgilityPack;
using ScrapySharp.Extensions;

namespace Koala.JiraTool.Core
{
    internal class TokenController : ITokenController
    {
        private readonly IHttpClient _httpClient;
        private readonly GlobalSettings _globalSettings;

        public TokenController(IHttpClient httpClient, GlobalSettings globalSettings)
        {
            _httpClient = httpClient;
            _globalSettings = globalSettings;
        }

        #region Implementation of ITokenController

        /// <summary>
        /// 获取当前上下文的Token。
        /// </summary>
        /// <returns>Token。</returns>
        public string GetToken()
        {
            var html = _httpClient.DownloadString(_globalSettings.LoginUrl);
            var document = new HtmlDocument();
            document.LoadHtml(html);
            var documentNode = document.DocumentNode;
            var node = documentNode.CssSelect("#log_out").FirstOrDefault();
            if (node == null)
                return string.Empty;
            var href = node.Attributes["href"].Value;
            const string identity = "atl_token=";
            var index = href.IndexOf(identity, StringComparison.OrdinalIgnoreCase);
            return href.Remove(0, index + identity.Length);
        }

        #endregion Implementation of ITokenController
    }
}